var distance = 1;
var service = {
    
    polygon: null,
    points: [],
    markers: [],
    siteAddress: null,
    setMarkers: function(){
        mapa.clearOverlays();
        center = new GLatLng(centrePoint.lat(), centrePoint.lng());
        center.pointOrder = 1;
        var latConv = center.distanceFrom(new GLatLng(center.lat() + 0.1, center.lng())) / 100;
        var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng() + 0.1)) / 100; 
        
        nodes = 40;
        new_radius = distance;
        CirclePoints = [];
        var step = parseInt(360 / nodes) || 10;
        var counter = 0;
        for (var i = 0; i <= 360; i += step) {
            var cLat = center.lat() + (new_radius / latConv * Math.cos(i * Math.PI / 180));
            var cLng = center.lng() + (new_radius / lngConv * Math.sin(i * Math.PI / 180));
            var point = new GLatLng(cLat, cLng);
            CirclePoints.push(point);
            counter++;
        } 
        
        var polygon = new GPolygon(CirclePoints, "#f33f00", 5, 1, "#ff0000", 0.2);
        mapa.addOverlay(polygon);
        $('#mainLon').val(centrePoint.lng())
        $('#mainLat').val(centrePoint.lat());
        this.addMarker(center);
    },

    setPolygon: function(){
        if(service.polygon != null){
            mapa.removeOverlay(service.polygon);
        }
        this.polygon = new GPolygon(this.points,'#ff0000',4,0.7,'#ff0000',0.2);
        mapa.addOverlay(this.polygon)
    },
    
    giveDistance: function(dist)
    {
        distance = dist;
        var center = new GLatLng($('#mainLat').val(), $('#mainLon').val())   
        var latConv = center.distanceFrom(new GLatLng(center.lat() + 0.1, center.lng())) / 100;
            var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng() + 0.1)) / 100; 
            
            nodes = 40;
            new_radius = distance;
            CirclePoints = [];
            var step = parseInt(360 / nodes) || 10;
            var counter = 0;
            for (var i = 0; i <= 360; i += step) {
                var cLat = center.lat() + (new_radius / latConv * Math.cos(i * Math.PI / 180));
                var cLng = center.lng() + (new_radius / lngConv * Math.sin(i * Math.PI / 180));
                var point = new GLatLng(cLat, cLng);
                CirclePoints.push(point);
                counter++;
            } 
            
            
            
            var polygon = new GPolygon(CirclePoints, "#f33f00", 5, 1, "#ff0000", 0.2);
            mapa.clearOverlays();
            var marker = new GMarker(center, {draggable: true});
            GEvent.addListener(marker, "dragend", function()
            {
                var center = marker.getPoint();
                center.pointOrder = 1;
                var latConv = center.distanceFrom(new GLatLng(center.lat() + 0.1, center.lng())) / 100;
                var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng() + 0.1)) / 100; 
                
                nodes = 40;
                new_radius = distance;
                CirclePoints = [];
                var step = parseInt(360 / nodes) || 10;
                var counter = 0;
                for (var i = 0; i <= 360; i += step) {
                    var cLat = center.lat() + (new_radius / latConv * Math.cos(i * Math.PI / 180));
                    var cLng = center.lng() + (new_radius / lngConv * Math.sin(i * Math.PI / 180));
                    var point = new GLatLng(cLat, cLng);
                    CirclePoints.push(point);
                    counter++;
                } 
                
                var polygon = new GPolygon(CirclePoints, "#f33f00", 5, 1, "#ff0000", 0.2);
                mapa.clearOverlays();
                $('#mainLon').val(center.lng());
                $('#mainLat').val(center.lat());
                mapa.addOverlay(marker);
                mapa.addOverlay(polygon);
            });
            mapa.addOverlay(marker);
            mapa.addOverlay(polygon);
    },
    
    addMarker: function(point){
        var marker = new GMarker(point, {draggable: true});
        if(point.pointOrder == undefined){
            alert('You have to set pointOrder of the mark. Action has been breaked.');
            return;
        }
        marker.pointOrder = point.pointOrder;
        mapa.addOverlay(marker);
        service.markers.push(marker);
        service.addPointToForm(point);

        GEvent.addListener(marker, "dragend", function()
        {
            var center = marker.getPoint();
            center.pointOrder = 1;
            var latConv = center.distanceFrom(new GLatLng(center.lat() + 0.1, center.lng())) / 100;
            var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng() + 0.1)) / 100; 
            
            nodes = 40;
            new_radius = distance;
            CirclePoints = [];
            var step = parseInt(360 / nodes) || 10;
            var counter = 0;
            for (var i = 0; i <= 360; i += step) {
                var cLat = center.lat() + (new_radius / latConv * Math.cos(i * Math.PI / 180));
                var cLng = center.lng() + (new_radius / lngConv * Math.sin(i * Math.PI / 180));
                var point = new GLatLng(cLat, cLng);
                CirclePoints.push(point);
                counter++;
            } 
            
            var polygon = new GPolygon(CirclePoints, "#f33f00", 5, 1, "#ff0000", 0.2);
            mapa.clearOverlays();
            $('#mainLon').val(center.lng());
            $('#mainLat').val(center.lat());
            mapa.addOverlay(marker);
            mapa.addOverlay(polygon);
        });
    },

    setCity: function(place){
        var address = place || $('#city').val();
        if (geocoder) {
            geocoder.getLatLng(address, function(point) {
                if (point) {
                    service.removeMarkers();
                    centrePoint = point;
                    service.setMarkers();
                    mapa.setCenter(point, 12);
                    $('#mainLon').value = point.lng();
                    $('#mainLat').value = point.lat();
                }
            });
        }
    },
    
    autocomplite: function(){
        
    },
    
    removeMarkers: function(){
        for(var i=0; i<service.markers.length; i++){
            mapa.removeOverlay(service.markers[i]);
        }
        $('.mapPoints').remove();
    },
    addNewMarkerToMap: function(){
        var pointsLen = service.points.length;

        if(!(this.points[pointsLen - 2].lat() == centrePoint.lat() && this.points[pointsLen - 2].lng() == centrePoint.lng())){
            var newPoint = new GLatLng(centrePoint.lat(),centrePoint.lng());
            newPoint.pointOrder = pointsLen - 1;

            this.points[pointsLen - 1] = newPoint;
            this.points.push(this.points[0]);

            this.addMarker(newPoint);
            this.setPolygon();
        }
    },

    addPointToForm: function(point){
        var $latInput, $lngInput, $form = $('#addServiceForm');
        
        $latInput = this.createInputForm(point);
        $latInput.attr('name', 'points[' + point.pointOrder + '][lat]');
        $latInput.attr('value', point.lat());
        $form.append($latInput);

        $lngInput = this.createInputForm(point);
        $lngInput.attr('name', 'points[' + point.pointOrder + '][lng]');
        $lngInput.attr('value', point.lng());
        $form.append($lngInput);
    },

    createInputForm: function(point){
        return $('<input>').attr('type', 'hidden')
                           .attr('class', 'mapPoints '+ point.pointOrder);
    },
    
    getChildCategories: function(ev, category){
        var $category =  $(category);
        this.getCategories({parent_id: $category.val()}, $category);
    },

    backToParentCategory: function(){
        var $category = $("#category");
        this.getCategories({child_id: $category.val()}, $category);
    },

    loadCategoriesToSecBox: function(ev, category){
        var $category =  $(category);
        this.getCategories({parent_id: $category.val(), combo: 'first'}, $('#categorySelectSec'));
    },
    
    loadCategoriesToThirdBox: function(ev, category){
        var $category =  $(category);
        this.getCategories({parent_id: $category.val(), combo: 'sec'}, $('#categorySelectThird'));
    },

    nextCategories: function(ev, category){
        var $category =  $(category);
        this.getCategories({parent_id: $category.val(), combo: 'third'}, $('#categorySelectThird'));

    },

    getCategories: function(params){
        if(service.siteAddress == null){
            service.setSite();
        }
        service.requestedCombo = params.combo;
        $.ajax({
            url: service.siteAddress + "ajax.php?view=serviceQuery&act=loadCategories",
            data: params,
            dataType: 'json',
            success: function(data){
                var $firstCombo = $('#categorySelectOne'),
                    $secCombo = $('#categorySelectSec'),
                    $thirdCombo = $('#categorySelectThird');
                switch (service.requestedCombo) {
                    case 'first':{
                        $secCombo.html('');
                        $thirdCombo.html('');
                        service.comboString = 'sec';
                        service.putCategories(data.catComboSec, $secCombo, data.secSelected);
                        service.comboString = 'first';
                        service.putCategories(data.catComboFirst, $firstCombo, data.firstSelected);
                        service.comboString = 'third';
                        service.putCategories(data.catComboThird, $thirdCombo, data.thirdSelected);
                        $thirdCombo.find('option:first').attr('selected', 'selected');
                    }break;
                    case 'sec':{
                        $thirdCombo.html('');
                        service.comboString = 'third';
                        service.putCategories(data.catComboThird, $thirdCombo, data.thirdSelected);
                        $thirdCombo.find('option:first').attr('selected', 'selected');
                    }break;
                    case 'third':{
                        service.comboString = 'sec';
                        service.putCategories(data.catComboSec, $secCombo, data.secSelected);
                        service.comboString = 'first';
                        service.putCategories(data.catComboFirst, $firstCombo, data.firstSelected);
                        service.comboString = 'third';
                        service.putCategories(data.catComboThird, $thirdCombo, data.thirdSelected);
//                        if(data.catComboThird.length > 0){
//                            $thirdCombo.find('option:first').attr('selected', 'selected');
//                        }
                    }break;
                    default:
                        break;
                }


            },
            error: function(data){
            }
        });
    },
    putCategories: function(categories, $combo, selected){
        var options = "";
        if(categories.length > 0 || categories.length == undefined){
            $.each(categories, function(id, name){
                options += '<option '+ (selected == id ? 'selected="selected" onclick="service.prepareToLoadCategories('+id +',\''+service.comboString+'\')"': '') +' value="'+id+'">'+name+'</option>';
            });
            $combo.html(options);
        }
    },
    prepareToLoadCategories: function(id, comboStr){
        service.getCategories({parent_id: id, combo: comboStr});
    },
    setSite: function(){
        service.siteAddress = $('#siteAddress').val();
    },

    showServiceBox: function(id){
        var company = $('#company_name-'+id).val(), companyText;
        $('#dialogTitle').html($('#name-'+id).val());
        $('#dialogText').html($('#desc-'+id).val());
        $('#pricePerHouer').html('Cena za godzinę pracy: '+$('#price_per_hour-'+id).val()+' zł');
        $('#pricePerAll').html('Cena za całą usługę: '+$('#price_per_service-'+id).val()+' zł');
        if(company == ""){
            companyText = "Nie(osobowa prywatna";
        }else{
            companyText = "Tak("+company+")";
        }
        $('#company').html('Czy firma: '+companyText);

        $('#dialWindow').dialog({
//            buttons: {'ok': function(){
//                    $(this).dialog("close");}
//            },
            resizable: false
        })
    },
    startSlider: function(){
        $( "#sliderDistance" ).slider({
                range: "max",
                min: 1,
                max: 35,
                value: 1,
                slide: function( event, ui ) {
                        $( "#distance" ).val( ui.value );
                        service.giveDistance(ui.value);
                }
        });
        $( "#distance" ).val( $( "#sliderDistance" ).slider( "value" ) );
    }
    
}